package com.wqiuqiu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wqiuqiu.common.constant.ProductConstant;
import com.wqiuqiu.gulimall.product.entity.AttrGroupEntity;
import com.wqiuqiu.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqiuqiu.common.PageUtils;
import com.wqiuqiu.common.Query;

import com.wqiuqiu.gulimall.product.dao.CategoryDao;
import com.wqiuqiu.gulimall.product.entity.CategoryEntity;
import com.wqiuqiu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    return menu1.getSort() - menu2.getSort();
                }).collect(Collectors.toList());
        return menus;
    }

    @Override
    public void removeBatchBuIds(List<Long> asList) {
        //TODO 删除逻辑
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, all));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return children;
    }

    @Override
    public Long[] getCatelogIdPaths(Long categoryId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPaths = getParentId(paths, categoryId);
        Collections.reverse(parentPaths);
        return parentPaths.toArray(new Long[parentPaths.size()]);
    }


    @CacheEvict(value = {"category"}, allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())){
            this.baseMapper.updateRelationCategory(category.getCatId(), category.getName());
        }
    }


    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getAllFristCatelog() {
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("cat_level", ProductConstant.enumCatelog.FRIST_CATELOG.getCode()));
        return list;

    }


    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelog() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> allFristCatelog = getParent_cid(list, 0L);
        Map<String, List<Catelog2Vo>> categoryJson = allFristCatelog.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l1 -> {
            List<CategoryEntity> childs1 = getParent_cid(list, l1.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (childs1 != null && childs1.size() > 0) {
                catelog2Vos = childs1.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setCatalog1Id(l1.getCatId().toString());
                    catelog2Vo.setName(l2.getName());
                    catelog2Vo.setId(l2.getCatId().toString());
                    //找三级分类
                    List<CategoryEntity> childs2 = getParent_cid(list, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                    if (childs2 != null && childs2.size() > 0) {
                        catelog3Vos = childs2.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                            catelog3Vo.setId(l3.getCatId().toString());
                            catelog3Vo.setName(l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return categoryJson;
    }

    public Map<String, List<Catelog2Vo>> getCatelog1() {
        String categoryJson = stringRedisTemplate.opsForValue().get("categoryJson");
        if (StringUtils.isNotEmpty(categoryJson)) {
            Map<String, List<Catelog2Vo>> map = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            log.info("沒有查询数据库。。。。");
            return map;
        } else {
            Map<String, List<Catelog2Vo>> catelogFromDB = getCatelogFromDB();
            log.info("查询数据库。。。。");
            return catelogFromDB;
        }
    }


    public Map<String, List<Catelog2Vo>> getCatelogFromDB() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> allFristCatelog = getParent_cid(list, 0L);
        Map<String, List<Catelog2Vo>> categoryJson = allFristCatelog.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l1 -> {
            List<CategoryEntity> childs1 = getParent_cid(list, l1.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (childs1 != null && childs1.size() > 0) {
                catelog2Vos = childs1.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setCatalog1Id(l1.getCatId().toString());
                    catelog2Vo.setName(l2.getName());
                    catelog2Vo.setId(l2.getCatId().toString());
                    //找三级分类
                    List<CategoryEntity> childs2 = getParent_cid(list, l2.getCatId());
                    List<Catelog2Vo.Catelog3Vo> catelog3Vos = null;
                    if (childs2 != null && childs2.size() > 0) {
                        catelog3Vos = childs2.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(l2.getCatId().toString());
                            catelog3Vo.setId(l3.getCatId().toString());
                            catelog3Vo.setName(l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(catelog3Vos);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //存入redis
        stringRedisTemplate.opsForValue().set("categoryJson", JSON.toJSONString(categoryJson), 1L, TimeUnit.DAYS);
        return categoryJson;
    }

    /**
     * 在指定的集合中找到给定id的子分类节点
     *
     * @param all      指定的集合
     * @param parentId 给定id
     * @return 子分类节点
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> all, Long parentId) {
        return all.stream().filter(item -> item.getParentCid().equals(parentId)).collect(Collectors.toList());
    }

    private List<Long> getParentId(List<Long> paths, Long categoryId) {
        paths.add(categoryId);
        CategoryEntity category = this.getById(categoryId);
        if (null != category && 0 != category.getParentCid()) {
            getParentId(paths, category.getParentCid());
        }
        return paths;
    }

}